<?php
/*Convert Functions For XML Fields to DB Fields*/
function GetCaseDBFieldsByXMLFields($XMLFields,$_LANG)
{
	$DBFields = array();
	foreach($XMLFields as $Item)
	{
		array_push($DBFields,$_LANG['CaseImport'][$Item]);
	}
	return $DBFields;
}

/*Get MustImport and Optional Import Fields*/
function GetCaseMustImportFields($_LANG)
{	
	$MustImportFields = $_LANG['CaseMustImportFields'];
	return $MustImportFields;
}
function GetCaseOptionalImportFields($_LANG)
{
	$OptionalImportFields = $_LANG['CaseOptionalImportFields'];
	return $OptionalImportFields;	
}

/*Filter out the ImportFields wiht MustImportFields and OptionalImportFields*/
function FilterCaseImportFields($ImportFields,&$FilteredImportFields,$MustImportFields,$OptionalImportFields)
{
	$CaseIDColumnNumber = 0;  // 初始化CaseID对应的列序号			
  
  //Filter the ImportFields with the MustImportFields and OptionalImportFields,
  if($ImportFields)
  {
  	//$Key是列序号,Value是列的名称
  	foreach($ImportFields as $Key => $Value)
   	{
   		//获取CaseID Field所在的列号 
    	if(trim($Value)=="CaseID")
      {
      		$CaseIDColumnNumber = $Key; //Case ID的Key
      }
      
      if(in_array(trim($Value),$MustImportFields) || in_array(trim($Value),$OptionalImportFields))
      {
          $FilteredImportFields[$Key] = $Value;
      } 	
    }
    $FilteredImportFields[] = 'ProjectID';
    $FilteredImportFields[] = 'ModuleID';
	}
	return 	$CaseIDColumnNumber;
}
/*Valiate the ProjectName,ModulePath and CaseTitle*/
function GetCaseValidateColumns($ItemRow,$ImportFieldArray)
{ 
    //判断Case的ProjectID、ModuleID和CaseTitle是否合法，并返回
    global $_LANG;
    $ProjectModules = array();
    $ProjectName = trim($ItemRow[array_search('ProjectName', $ImportFieldArray)]);

    $CaseProjectRow = dbGetRow('TestProject', 'ProjectID', "ProjectName='{$ProjectName}'");

    if($CaseProjectRow)
    {
       $ProjectModules['ProjectID'] = $CaseProjectRow['ProjectID'];
    }
    else{
        $ProjectModules['error'] = $_LANG['ImportMsg']['project_not_existed'];
        return $ProjectModules;
    }

    if(!in_array($ProjectModules['ProjectID'],array_keys(baseGetUserACL($_SESSION['TestUserName']))) )
    {
        $ProjectModules['error'] = $_LANG['ImportMsg']['project_no_permission'];
        return $ProjectModules;
    }



    $ProjectModules['ModuleID']=-1; //初始化为-1
    $ModuleListArray = testGetProjectModuleList($ProjectModules['ProjectID'],'Case');
    foreach($ModuleListArray as $Item)
    {
         if(trim($ItemRow[array_search('ModulePath', $ImportFieldArray)]) == trim($Item['NamePath']))
         {
             $ProjectModules['ModuleID'] = $Item['ModuleID'];
             break;
         }
    }

    if($ProjectModules['ModuleID']==-1)//模块路径不存ｿ
    {
        $ProjectModules['error'] = $_LANG['ImportMsg']['module_not_existed'];
        return $ProjectModules;
    }
       
    $ProjectModules['CaseTitle'] = trim($ItemRow[array_search('CaseTitle', $ImportFieldArray)]);

    if(!$ProjectModules['CaseTitle'])//Case标题为空
    {
        $ProjectModules['error'] = $_LANG['ImportMsg']['title_empty'];
        return $ProjectModules;
    }

    return $ProjectModules;
}
/* Get CaseInfo of Case with ID:CaseID*/
function GetCaseIDInfo($CaseID)
{
	$CaseInfo = dbGetRow('CaseInfo', 'CaseID', "CaseID='{$CaseID}'");
	return $CaseInfo;
}

/*Copy the SrcCaseInfo to $DstCaseInfo*/
function CopyCaseInfo($SrcCaseInfo,&$DstCaseInfo,$_LANG)
{
	foreach($_LANG['CaseFields'] as $Key => $Value)
	{
			$DstCaseInfo[$Key] = $SrcCaseInfo[$Key];
	}
}

/* Check Import Field's Value*/
function CheckCaseImportFieldValue($FieldName,$Value)
{
		$Result = false;
		switch($FieldName)
		{
      case 'AssignedTo':
        if(trim($Value)=='Active')
        {
        		$Result = true;
        }
        elseif(dbGetRow('TestUser', 'UserName', "UserName='{$Value}'"))
        {
        		$Result = true;
        }        
        break;
      case 'CasePriority':
      	if (is_numeric($Value) && (int)($Value)>=0 && (int)($Value)<count($_LANG['CasePriorities']))
        {
        		$Result = true;
        }
        break;
      case 'CaseStatus':
      	if(in_array($Value,$_LANG['CaseStatuses']))
        {
        		$Result = true;
        }
        break;
      default:
        $Result = true;
    }
    return $Result;      
}

/* Update CaseInfo of Case with ID:CaseID*/
function UpdateCaseInfo($CaseID,$ImportFields,$ImportItem,$ValidateColumns,$_LANG)
{
	//Get the CaseInfo of Case wiht ID
	$QueryInfo = dbGetRow('CaseInfo', '', "CaseID='{$CaseID}'"); //取出要修改的Case信息
	
	//Copy the CaseInfo to EditKeyValue
	$EditKeyValue = array();
	CopyCaseInfo($QueryInfo,$EditKeyValue,$_LANG);
                        
	//Check And Set The Import Field Value 
	$UpdateFields = array();
  foreach($ImportFields as $Key => $Value)
  {
    $Value = trim($Value);
    $ImportItem[$Key] = trim($ImportItem[$Key]);
    
    //Check Case ImportFieldValue, 
    if(CheckCaseImportFieldValue($Value,$ImportItem[$Key]) === true)
    {
    	$UpdateFields[$Key] = $Value;
    	if($Value == 'ProjectID')
    	{
    		$ImportItem[$Key] = $ValidateColumns['ProjectID'];	
    	}
    	elseif($Value == 'ModuleID')
    	{
    		$ImportItem[$Key] =  $ValidateColumns['ModuleID'];
    	}
    }   
  }//end foreach
  //print_r($UpdateFields);exit;   
    
	foreach($UpdateFields as $Key => $Value)
  {
  	$EditKeyValue[$Value] = addslashes($ImportItem[$Key]);
  }
  $EditKeyValue['TestUserName'] = sysAddSlash($_SESSION['TestUserName']);
  $EditKeyValue['LastActionID'] = testGetLastActionID('Case',$EditKeyValue['CaseID']);
                           
	//print_r($EditKeyValue);exit;
  testEditCase($EditKeyValue);
  unset($UpdateFields);
  unset($EditKeyValue);
}

/*Add a new Case In DB*/
function AddNewCase($ImportFields,$ImportItem,$ValidateColumns,$_LANG)
{
	$InsertFields = array();
  foreach($ImportFields as $Key => $Value)
  {
  	$ImportItem[$Key]=trim($ImportItem[$Key]);
    $Value = trim($Value);
    if($Value!='CaseID')
    {
    	$InsertFields[$Key] = $Value;
    	//Check Case ImportFieldValue, 
    	if(CheckCaseImportFieldValue($Value,$ImportItem[$Key]) === true)
    	{
    		$InsertFields[$Key] = $Value;
    		if($Value == 'ProjectID')
    		{
    			$ImportItem[$Key] = $ValidateColumns['ProjectID'];	
    		}
    		elseif($Value == 'ModuleID')
    		{
    			$ImportItem[$Key] =  $ValidateColumns['ModuleID'];
    		}
    	}
    }//end if
	}//end foreach

	//Set the InsertKeyValue
	$InsertKeyValue = array();
  foreach($InsertFields as $Key => $Value)
  {
  	$InsertKeyValue[$Value] = addslashes($ImportItem[$Key]);
  }
  if(!array_search('CasePriority',$InsertFields))
  	$InsertKeyValue['CasePriority'] = '0';
  if(!array_search('CaseType',$InsertFields))
  	$InsertKeyValue['CaseType'] = 'Functional';
  if(!array_search('CaseMethod',$InsertFields))
  	$InsertKeyValue['CaseMethod'] ='Automation';
  if(!array_search('AssignedTo',$InsertFields))
  	$InsertKeyValue['AssignedTo'] ='Active';
  if(!array_search('DisplayOrder',$InsertFields))
  	$InsertKeyValue['DisplayOrder'] = 0;                        
  $InsertKeyValue['TestUserName'] = sysAddSlash($_SESSION['TestUserName']);
  
  testOpenCase($InsertKeyValue);
  unset($InsertKeyValue);
  unset($InsertFields);
}

/*Import the CaseList to the DB*/
function ImportCases($ImportItemList,$ImportFields,$ImportFieldArray,$CaseIDColumn,$_LANG)
{
        $ImportTotalItem = 0;
        $ImportSuccessItem = 0;
        $ImportFailItem = 0;
        $ErrorMsg = '';

         foreach($ImportItemList as $ImportItemListKey =>$ImportItemListValue)
         {     
              $ImportTotalItem = $ImportTotalItem + 1;

              if($ImportItemListValue&&count($ImportFields)==count($ImportItemListValue))
              {   
                 $ValidateColumns = GetCaseValidateColumns($ImportItemListValue,$ImportFieldArray); //判断字段的合法位
                 if(!isset($ValidateColumns['error']))
                 { 
                 			//必填字段合法
                      $ImportSuccessItem = $ImportSuccessItem + 1;
                      $CaseID = $ImportItemListValue[$CaseIDColumn];
                      $CaseRow = GetCaseIDInfo($CaseID);
                      if($CaseRow)
                      {
                      	 //CaseID存在，则更新Case相关消息
                      	 UpdateCaseInfo($CaseID,$ImportFieldArray,$ImportItemListValue,$ValidateColumns,$_LANG); 
                      }//end edit case
		      						else 
		      						{ 
		      								//CaseID不存在，则新增Case         
                          AddNewCase($ImportFieldArray,$ImportItemListValue,$ValidateColumns,$_LANG);
                      }
                 }
                 else
                 {
                            $ErrorMsg .= 'Import row '.$ImportTotalItem.' failed:['.$ValidateColumns['error'].']\n';
                 }
              }
         }
         $ImportFailItem = $ImportTotalItem-$ImportSuccessItem;
         $FinishAlert = str_replace('{param0}',$ImportTotalItem, $_LANG['ImportFinished']);
         $FinishAlert = str_replace('{param1}',$ImportSuccessItem, $FinishAlert);
         $FinishAlert = str_replace('{param2}',$ImportFailItem, $FinishAlert);
         if("" != $ErrorMsg)
         {
                $ErrorMsg = '\n'.$ErrorMsg;
         }
         sysObFlushJs("alert('{$FinishAlert}{$ErrorMsg}');");
}
?>
